import { message } from 'antd'

/* 视频截帧，当封面 */
export interface FrameData {
    blob: Blob;
    url: string;
}

/* canvas画帧 */
function drawVideo(vdo: HTMLVideoElement): Promise<FrameData> {
    return new Promise((resolve, reject) => {
        const cvs = document.createElement('canvas');
        const ctx = cvs.getContext('2d');
        if (!ctx) {
            throw new Error('无法获取CanvasRenderingContext2D');
        }
        cvs.width = vdo.videoWidth;
        cvs.height = vdo.videoHeight;
        ctx.drawImage(vdo, 0, 0, cvs.width, cvs.height);
        /* 如果视频本来就没画面的话，就是画不出来： cvs.width, cvs.height都是0 */
        if (cvs.width === 0 || cvs.height === 0) {
            message.info('视频可能无画面，无法生成封面')
            reject({
                blob: '',
                url: '',
            })
        }
        cvs.toBlob((blob) => {
            if (blob) {
                resolve({
                    blob,
                    url: URL.createObjectURL(blob),
                });
            } else {
                throw new Error(`无法获取Blob:Canvas toBlob 返回了${blob}`);
            }
        })
    })
}

/**
 * 
 * @param {视频文件} vdoFile 
 * @param {时间单位,默认是0,就是第几帧} time 
 */
export function captureFrame(vdoFile: File, time: number = 0) {
    return new Promise((resolve) => {
        const vdo = document.createElement('video');
        vdo.currentTime = time;
        vdo.muted = true;
        vdo.autoplay = true;
        vdo.oncanplay = async () => {
            const frame = await drawVideo(vdo);
            resolve(frame);
        }
        vdo.src = URL.createObjectURL(vdoFile);

    })
}

/**
 * @param {视频文件} file
 * @returns {Promise<duration>}
 */
//获取视频文件（寄）
export function getVideoDuration(file: File) {
    return new Promise((resolve, reject) => {
        const video = document.createElement('video');
        video.preload = 'metadata';
        video.onloadedmetadata = () => {
            window.URL.revokeObjectURL(video.src); // 释放资源
            resolve(video.duration);
        };
        video.onerror = reject;
        video.src = URL.createObjectURL(file); // 创建视频文件的 URL
    });
}